from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
class ImageCodeView(View):
    def get(self,request,uuid):#1.接收路由中的uuid
        #2.生成图片验证码和图片二进制
        from libs.captcha.captcha import captcha
        text,image=captcha.generate_captcha()
        #3. 将图片保存到内存中通过redis
        #3.1进行redis的连接
        from django_redis import get_redis_connection
        redis_cli=get_redis_connection('code')
        #3.2指令操作，设置验证码过期时间
        redis_cli.setex(uuid,100,text)
        #4.返回图片二进制
        from django.http import HttpResponse
        return HttpResponse(image,content_type='image/jpeg')
class Ceshi2(View):
    def get(self,request):
        from django.http import HttpResponse

        return HttpResponse('ok')
class SmsCodeView(View):
    def get(self,request,mobile):
        # 1.接收参数
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        # 2.校验参数
        if not all([image_code,uuid]):
            return JsonResponse({'code':400,'errmsg':'参数不足'})
        # 3.校验图片验证码
        # 3.1连接redis
        from django_redis import get_redis_connection
        redis_cli=get_redis_connection('code')
        # 3.2获取redis中的图片验证码
        redis_image_code=redis_cli.get(uuid)
        if redis_image_code is None:
            return JsonResponse({'code':400,'errmsg':'图片验证码过期'})
        # 3.3校验图片验证码
        if image_code.lower()!=redis_image_code.decode().lower():
            return JsonResponse({'code':400,'errmsg':'图片验证码错误'})
        #提取发送短信的标记，如果标记存在，则不发送短信
        send_flag=redis_cli.get(f'send_flag_{mobile}')
        if send_flag:
            return JsonResponse({'code':400,'errmsg':'短信发送过于频繁'})
        # 4.生成短信验证码
        from random import randint
        sms_code='%06d'%randint(1,999999)
        #管道分3步
        #1，创建管道
        pipeline=redis_cli.pipeline()
        #2.管道收集指令
        pipeline.setex(mobile,300,sms_code)
        pipeline.setex(f'send_flag_{mobile}',60,1)
        #3.执行管道
        pipeline.execute()
        # # 5.保存短信验证码到redis中
        # redis_cli.setex(mobile,300,sms_code)
        # #添加一个发送标记，有效期是60s，避免频繁发送短信
        # redis_cli.setex(f'send_flag_{mobile}',60,1)
        # 6.发送短信验证码
        from libs.yuntongxun.sms import CCP
        ccp=CCP()
        ccp.send_template_sms(mobile,[sms_code,5],1)
        # 7.返回响应
        return JsonResponse({'code':0,'errmsg':'ok'})